package com.jk.interceptor;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * &lt;pre&gt;项目名称：jk-pay
 * 类名称：
 * 创建人：李金春
 * 手机号：18839726119
 * 创建时间：2017-12-26 20:18:59
 * 修改人：李金春
 * 修改时间：2017-12-26 20:19:09
 * 修改备注：
 */
@Order(1)
@WebFilter(filterName="corsFilter",urlPatterns = "/*")
public class MyFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化方法");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //设置允许跨域的ip与端口号
        response.setHeader("Access-Control-Allow-Origin","*");
        //设置允许跨域的方法
        response.setHeader("Access-Control-Allow-Methods","POST,GET,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Allow-Credentials","true");
        System.out.println(request.getMethod());
        if("OPTIONS".equals(request.getMethod())){
            response.setStatus(204);
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁方法");
    }
}
